package com.yangxk.kadmin.web.config;

import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.yangxk.kadmin.web.common.converter.String2DateConveter;
import com.yangxk.kadmin.web.common.interceptor.AuthInterceptor;
import com.yangxk.kadmin.web.common.interceptor.DemoModelInterceptor;
import com.yangxk.kadmin.web.common.interceptor.LimitInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${k-admin.demo.model}")
    private boolean demoModel;

    /**
     * 注册日期转换器
     * create by yangxk 2018/10/22 20:11
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new String2DateConveter());
    }

    /**
     * 注册拦截器
     * create by yangxk 2018/10/22 20:11
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LimitInterceptor())
                .addPathPatterns("/**");

        // 注册权限拦截器
        registry.addInterceptor(new AuthInterceptor())
                .addPathPatterns("/**");

        // 演示模式拦截器
        if (demoModel) {
            registry.addInterceptor(new DemoModelInterceptor())
                    .addPathPatterns("/**");
        }
    }

    /**
     * 重写jackson序列化Long时的操作
     * create by yangxk 2018/10/22 20:11
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        /**
         * 从已注册的converter中获取MappingJackson2HttpMessageConverter并配置module
         * 该module实现了json序列化时将Long转为String
         * 采用这种方式实现，可以在application.properties中对json进行配置
         * 如果新建MappingJackson2HttpMessageConverter并添加至converters中，则需要在代码中配置jackson序列化的相关配置
         */
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter cvt = (MappingJackson2HttpMessageConverter)converter;
                SimpleModule simpleModule = new SimpleModule();
                simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
                simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
                cvt.getObjectMapper().registerModule(simpleModule);
                break;
            }
        }
    }

}
